package com.company.crm.workbench.web.controller;

import com.company.crm.commons.constants.Constants;
import com.company.crm.commons.domain.ReturnObject;
import com.company.crm.commons.util.DateUtils;
import com.company.crm.commons.util.UUIDUtils;
import com.company.crm.settings.domain.User;
import com.company.crm.settings.service.UserService;
import com.company.crm.workbench.domain.Activity;
import com.company.crm.workbench.domain.ActivityRemark;
import com.company.crm.workbench.service.ActivityRemarkService;
import com.company.crm.workbench.service.ActivityService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.security.x509.AVA;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 作者：王磊栋
 * 2021/4/17
 */
@Controller
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserService userService;

    //跳入市场活动
    @RequestMapping("/workbench/activity/index.do")
    public String skipActivity(Model model){
        List<User> userList = userService.selectAll();
        model.addAttribute("userList", userList);
        return "workbench/activity/index";
    }
    @RequestMapping("/workbench/activity/queryActivityForPageByCondition.do")
    @ResponseBody
    public Object queryActivityForPageByCondition(@RequestParam Map<String,Object> map){
        String sNo = (String)map.get("pageNo");
        String sSize = (String) map.get("pageSize");
        Integer pageSize = Integer.valueOf(sSize);
        Integer pageNo = Integer.valueOf(sNo);
        map.put("beginNo", (pageNo-1)*pageSize);
        map.put("pageSize", pageSize);
        List<Activity> activityList = activityService.selectActivityByPageAndOther(map);
        long totalRows = activityService.selectAllActivitiesCountsByConditions(map);
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("activityList", activityList);
        //需要用到总条数
        returnMap.put("totalRows", totalRows);
        return returnMap;
    }

    //增加活动
    //workbench/activity/saveCreateActivity.do
    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    @ResponseBody()
    public Object saveCreateActivity(Activity activity){
        ReturnObject ro = new ReturnObject();
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        //创建者怎么办
        activity.setCreateBy(activity.getOwner());
        int result = activityService.createActivity(activity);
        if (result>0){
            ro.setCode(Constants.LOGIN_CODE_SUCCESS);
        }else {
            ro.setCode(Constants.LOGIN_CODE_FAIL);
            ro.setMessage("创建失败！");
        }
        return ro;
    }

    //删除市场活动
    @RequestMapping("/workbench/activity/deleteActivityByIds.do")
    @ResponseBody()
    public Object deleteActivityByIds(String[] id){
        ReturnObject ro = new ReturnObject();
        int result = activityService.deleteActivityByIDs(id);
        if (result>0){
            ro.setCode(Constants.LOGIN_CODE_SUCCESS);
        }else {
            ro.setCode(Constants.LOGIN_CODE_FAIL);
            ro.setMessage("删除失败！");
        }
        return ro;
    }

    //点击主页面更新把这个id查询的数据封装到返回给ajax请求。
    @RequestMapping("/workbench/activity/editActivity.do")
    @ResponseBody()
    public Object editActivity(String id){
        Activity activity = activityService.queryActivityById(id);
        return activity;
    }

    //点击弹窗的更新发送的请求
    @RequestMapping("/workbench/activity/saveEditActivity.do")
    @ResponseBody()
    public Object saveEditActivity(Activity activity){
        ReturnObject ro = new ReturnObject();
        activity.setEditBy(activity.getOwner());
        activity.setEditTime(DateUtils.formatDateTime(new Date()));

        int result = activityService.updateActivity(activity);
        if (result>0){
            ro.setCode(Constants.LOGIN_CODE_SUCCESS);
        }else{
            ro.setMessage("更新失败");
            ro.setCode(Constants.LOGIN_CODE_FAIL);
        }
        return ro;
    }
    //批量下载
    @RequestMapping("/workbench/activity/exportAllActivity.do")
    public void exportAllActivity(HttpServletRequest request, HttpServletResponse response){
        OutputStream outputStream =null;
        Activity activity = null;
        //查询所有的活动
        List<Activity> activityList = activityService.selectAllActivity();
        //创建工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建表文件
        HSSFSheet sheet = wb.createSheet("市场活动列表");
        //创建第一行，并设置名字
        HSSFRow row = sheet.createRow(0);
        //创建单元格
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("编号");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("活动名字");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("花销");
        cell= row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("x修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        //设置样式
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //使用变量的方式进行天聪
        for (int i = 0; i < activityList.size(); i++) {
            activity =activityList.get(i);
            //创建第二行
            row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getId());

            cell = row.createCell(1);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getOwner());

            cell = row.createCell(2);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getName());

            cell =row.createCell(3);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getStartDate());

            cell = row.createCell(4);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getEndDate());

            cell = row.createCell(5);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCost());

            cell = row.createCell(6);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getDescription());

            cell = row.createCell(7);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCreateTime());


            cell = row.createCell(8);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCreateBy());


            cell = row.createCell(9);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getEditTime());

            cell = row.createCell(10);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getEditBy());

        }
        response.setContentType("application/octet-stream;charset=UTF-8");
        //中文的文件名不能被识别
        String fileName = null;
        try {
            fileName = URLEncoder.encode("市场活动", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.addHeader("Content-Disposition", "attachment;filename="+fileName+".xls");

        try {
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    //选着相对应的
    @RequestMapping("/workbench/activity/exportActivitySelective.do")
    public void  exportActivitySelective(String[] id, HttpServletRequest request, HttpServletResponse response) {
        List<Activity> activityList = activityService.selectActivityByIds(id);
        //创建工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        //设置样式
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //创建表文件
        HSSFSheet sheet = wb.createSheet("市场活动列表");
        //创建第一行，并设置名字
        HSSFRow row = sheet.createRow(0);
        //创建单元格
        HSSFCell cell = row.createCell(0);
        /*cell.setCellStyle(cellStyle);
        cell.setCellValue("编号");*/
        /*cell = row.createCell(1);*/
        /*cell.setCellStyle(cellStyle);
        cell.setCellValue("所有者");*/
        /*cell = row.createCell(2);*/
        cell.setCellStyle(cellStyle);
        cell.setCellValue("活动名字");
        cell = row.createCell(1);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("开始日期");
        cell = row.createCell(2);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("结束日期");
        cell = row.createCell(3);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("花销");
        cell= row.createCell(4);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("描述");
       /* cell = row.createCell(7);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellStyle(cellStyle);*/
/*
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("修改者");
*/


        Activity activity = null;
        //使用变量的方式进行填充
        for (int i = 0; i < activityList.size(); i++) {
            activity =activityList.get(i);
            //创建第二行
            row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getName());

            cell = row.createCell(2);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getStartDate());

            cell = row.createCell(2);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getEndDate());

            cell =row.createCell(3);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCost());

            cell = row.createCell(4);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getDescription());

           /* cell = row.createCell(5);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCost());

            cell = row.createCell(6);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getDescription());

            cell = row.createCell(7);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCreateTime());


            cell = row.createCell(8);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getCreateBy());


            cell = row.createCell(9);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getEditTime());


            cell = row.createCell(10);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(activity.getEditBy());*/

        }
        //设置响应的文本类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //中文的文件名不能被识别
        String fileName = null;
        try {
            //使用urlEncoder进行设置一个名字的编码方式。
            fileName = URLEncoder.encode("市场活动", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.addHeader("Content-Disposition", "attachment;filename="+fileName+".xls");
         OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            wb.write(outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //从excel中导入文件
    @RequestMapping("/workbench/activity/importActivity.do")
    @ResponseBody
    public Object importActivity(String username,MultipartFile activityFile,HttpSession session) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //拿到文件的输入流
        InputStream is = activityFile.getInputStream();
        //拿到session里的user
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //把表格中每一条数据都封装到activity稽核部中
        List<Activity> activityList = new ArrayList<>();
        Activity activity = null;
        //通过流创建工作簿
        HSSFWorkbook wb = new HSSFWorkbook(is);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row =null;
        HSSFCell cell = null;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            activity = new Activity();
            activity.setId(UUIDUtils.getUUID());
            activity.setOwner(user.getId());
            activity.setCreateBy(user.getId());
            activity.setCreateTime(DateUtils.formatDateTime(new Date()));
            row = sheet.getRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                cell = row.getCell(j);
                String value = this.getCellValue(cell);
                if (j==0){
                    activity.setName(value);
                }
                if (j==1){
                    activity.setStartDate(value);
                }
                if (j==2){
                    activity.setEndDate(value);
                }
                if (j==3){
                    activity.setCost(value);
                }
                if (j==4){
                    activity.setDescription(value);
                }
            }
            activityList.add(activity);
        }
        int count = activityService.insertByList(activityList);
        if (count>0){
            map.put("code",Constants.LOGIN_CODE_SUCCESS );
            map.put("count", count);
        }else {
            map.put("massage", "导入失败请检查文件是否符合要求");
        }
        return map;
    }

        private String getCellValue(HSSFCell cell) {
            String value ="";
            switch (cell.getCellType()){
                case HSSFCell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    value = cell.getBooleanCellValue()+"";
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    value = cell.getNumericCellValue()+"";
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    value = cell.getCellFormula()+"";
                    break;
                default:
                    value="";
            }
            return value;
        }

    //              ====备注=====
    @Autowired
    private ActivityRemarkService activityRemarkService;

    //按照创建时间显示说有的评论
    //处理每一个活动的超链接
    @RequestMapping("/workbench/activity/detailActivity.do")
    public String detailActivity(String id,Model model){
        Activity activity = activityService.queryActivityById(id);
        List<ActivityRemark> remarkList = activityRemarkService.selectAllActivityRemarkById(activity.getId());
        model.addAttribute("activity",activity);
        model.addAttribute("remarkList", remarkList);
        return "workbench/activity/detail";
    }

    //添加备注
    @RequestMapping("/workbench/activity/saveCreateActivityRemark.do")
    @ResponseBody()
    public Object saveCreateActivityRemark(ActivityRemark activityRemark, HttpSession session){
        /*String id = UUIDUtils.getUUID();*/
        activityRemark.setId(UUIDUtils.getUUID());
        activityRemark.setCreateTime(DateUtils.formatDateTime(new Date()));
        activityRemark.setCreateBy(((User)session.getAttribute(Constants.SESSION_USER)).getId());
        System.out.println(activityRemark.getId());
        activityRemark.setEditFlag("0");
        int result = activityRemarkService.insertActivityRemark(activityRemark);
        //System.out.println(id);
        ReturnObject returnObject = new ReturnObject();
        if (result>0){
            returnObject.setCode(Constants.LOGIN_CODE_SUCCESS);
            //通过活动的id来找所有的备注
            //activityRemarkService.selectAllActivityRemarkById(activityRemark.getId())
            //需要返回刚才插入的activityRemark
            returnObject.setResData(activityRemark);
        }else{
            returnObject.setCode(Constants.LOGIN_CODE_FAIL);
            returnObject.setMessage("保存失败");
        }
        return returnObject;


    }

    //根據id来删除备注
    @RequestMapping("workbench/activity/deleteActivityRemarkById.do")
    @ResponseBody()
    public Object deleteActivityRemarkById(String id){
        ReturnObject ro = new ReturnObject();
        int result = activityRemarkService.deleteActivityRemark(id);
        if (result>0){
            ro.setCode(Constants.LOGIN_CODE_SUCCESS);
        }else{
            ro.setCode(Constants.LOGIN_CODE_FAIL);
            ro.setMessage("删除失败");
        }
        return ro;
    }

    //更新备注neiroing
    @RequestMapping("/workbench/activity/saveEditActivityRemark.do")
    @ResponseBody()
    public Object saveEditActivityRemark(ActivityRemark activityRemark){
        ReturnObject returnObject = new ReturnObject();
        int result = activityRemarkService.updateActivityRemark(activityRemark);
        if (result>0){
            returnObject.setCode(Constants.LOGIN_CODE_SUCCESS);
            Map<String,Object> map = new HashMap<>();
            map.put("editTime", DateUtils.formatDateTime(new Date()));
            returnObject.setResData(map);
        }else {
            returnObject.setCode(Constants.LOGIN_CODE_FAIL);
            returnObject.setMessage("更新失败");
        }
        return  returnObject;
    }

}
